/*
 *   Copyright (C) 2008 - 2009  FireBalls
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// includes
#include "FPS.h"

// set the instance to 0
FPS* FPS::instance = 0;

FPS* FPS::singleton()
{
    // create a Guard object to make sure the instance is deleted after use.
    static Guard guard;

    // Only create an object if there isn't already one.
    if(instance == 0)
        // new instance
        instance = new FPS();

    return instance;
}

void FPS::Init(unsigned char timePerRound, const char* path)
{
    interval = timePerRound;
    logFPS = new Log;
    logFPS->OpenFile(path);
    logActive = true;
    next = 0;
    startCount = 0;
}

void FPS::Init(unsigned char timePerRound)
{
    interval = timePerRound;
    logActive = false;
    next = 0;
    startCount = 0;
}

void FPS::Loop()
{
    /*
     * get the current time
     * note: it's the time in ms since the programm started
     */
    now = SDL_GetTicks();

    /*
     * FPS Calculation
     * only if the log is active
     */
    if(logActive)
    {
        // if one second since the last time
        if(now - startCount >= 1000)
        {
            // print the fps
            logFPS->Write(count);
            logFPS->Endl();

            // reset the start time
            startCount = now;

            // reset counter
            count = 0;
        }
        count++;
    }

    /*
     * Delay Calculation
     * if this is the first loop
     */
    if(next == 0)
    {
        next = now;
        startCount = now;
    }

    // if there is time left
    if(now < next)
        // delay the game for exacly the time that is left
        SDL_Delay(next - now);
    else
        /*
         * it took longer than interval to execute the last round
         * to keep up set next to now
         */
        next = now;

    /*
     * add interval to next
     * next should be  now + interval
     */
    next += interval;
}
